import { Injectable } from '@angular/core';
import { AppConfig } from "../config";
import { Http,Headers } from "@angular/http";
import { MenuFavorite } from "../entity/menu_favorite.model";
import { InterceptorService } from '../service/interceptor/interceptor-service';

@Injectable()
export class MenuFavoriteService {
    private readonly param = "menuFavorites";
    private get url(): string {
      return `${AppConfig.APP_RESTFUL}/${this.param}`;
    }
    constructor(private http: InterceptorService) { }


  /**
   * 创建菜单
   * 
   * @param {Menu} menu 
   * @returns {Promise<Menu>} 
   * @memberof MenuService
   */
  public create(menuFavorite: MenuFavorite): Promise<MenuFavorite> {
    return this.http.post(this.url, JSON.stringify(menuFavorite))
      .toPromise()
      .then(res => {
        try {
          let result = res.json();
          switch (result.code) {
            case "200":
              return result.data as MenuFavorite;
            case "-1":
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
      .catch(this.handleError);
  }

  /**
   * 批量更新菜单
   * 
   * @param {Menu} menu 
   * @returns {Promise<Menu>} 
   * @memberof MenuService
   */
  public batchUpdate(menuFavorites: MenuFavorite[]): Promise<MenuFavorite[]> {
    const url = `${this.url}/sysMenuFavorites`;
    return this.http.put(url, JSON.stringify(menuFavorites))
      .toPromise()
      .then(() => menuFavorites)
      .catch(this.handleError);
  }

  /**
   * 批量删除
   * 
   * @param {number[]} menuIds 
   * @returns {Promise<boolean>} 
   * @memberof MenuService
   */
  public batchDelete(favoriteIds: number[]): Promise<boolean> {
    const apiUrl = `${this.url}?items=${favoriteIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        try {
          let result = response.json();
          switch (result.code) {
            case "200":
              return true;
            case "-1":
              throw new Error(result.message);
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }



  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }

}


// WEBPACK FOOTER //
// ./src/app/service/menu_favorite.service.ts